<?php

class Json {
    private $param = null;
    private $json = '';
    
    public function getJson() {

        
        return $this->json;
    }
    
    public function getParam() {
        return $this->param;
    }

    public function decode( $json ){
        $this->json = $json;
        
		mb_internal_encoding("UTF-8");
		mb_regex_encoding('UTF-8');

        $this->json = rawurldecode( $this->json );

		/*
		//Decrypt
		if( CEnv::is_encryption() ) {
			WriteLog(PEAR_LOG_DEBUG, __FILE__.':'.__LINE__, "#GET_CONF,======Encyption Enable=====" );
			if( IsProtoNeedDecryption( $PROTO_ROW ) ) {	
				$PARAM_ROW = CEncryption::Decrypt($PLAYER_ID, $PARAM_ROW, $nPublishCode);
			}
			else{
				//BASE64 decode
				$PARAM_ROW = base64_decode($PARAM_ROW);
				WriteLog(PEAR_LOG_DEBUG, __FILE__.':'.__LINE__, "#GET_CONF,skip decrypt by " . $PROTO_ROW );
			}
		}
		else{
			//BASE64 decode
			$PARAM_ROW = base64_decode($PARAM_ROW);
		}
		*/

		//$json = base64_decode($json);

		// Strip the string of illegal characters that interupts json.
		$this->json = str_replace(array("\n","\r"),"\\n",$this->json);
		$this->json = preg_replace('/([{,]+)(\s*)([^"]+?)\s*:/','$1"$3":',$this->json);
		$this->json = preg_replace('/(,)\s*}$/','}',$this->json);
		$this->json = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $this->json);

		Logs::Debug("#URL_AF_TRIM,PARAM:".$this->json );
		
		$this->param = json_decode($this->json);

		return $this;
	}
    
    public function encode( $param, $options = 0, $unescapee_unicode = true ) {
        $this->param = $param;
        $this->json = json_encode( $this->param, $options );
        if ( $unescapee_unicode ) {
            $this->json = $this->unicode( $this->json );
            $this->json = preg_replace( '/\\\\\//', '/', $this->json );
        }

        // encrypt the json data.
        /*
         if( CEnv::is_encryption() ) {
         echo CEncryption::EncryptReceive($strJSON, $nPublishCode);
         }
         else {
         echo $strJSON;
         }
         */
        
        return $this;
    }

    private function unicode( $str ) {
        return preg_replace_callback( "/\\\\u([0-9a-zA-Z]{4})/", "Json::encode_callback", $str );
    }

    public static function encode_callback( $matches ) {
        return mb_convert_encoding( pack( "H*", $matches[1] ), "UTF-8", "UTF-16" );
    }

}
